package com.demo.morning;

/**
 * @ClassName UnsafeBuyTicket
 * @Description TODO
 * @Author tianqinglong
 * @Date 9:56 2022/7/13
 * @Version 1.0
 **/
//不安全的买票
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket b = new BuyTicket ();
        new Thread(b, "a").start();
        new Thread(b, "b").start();
        new Thread(b, "c").start();
    }

}

class BuyTicket implements Runnable {
    //票数
    private int ticketNums = 10;
    boolean flag = true;//外部停止方式

    @Override
    public void run() {
        //
        while (flag) {
            buy();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }


    }

    private synchronized void buy() {
        // 判断是否有票
        if (ticketNums <= 0) {
            flag = false;
            return;
        }
        // 模拟延时

        // 买票
        System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums-- + "张票");
    }

}

